package com.csair.platform.cit.service.biz.impl.sb;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csair.invoice.common.base.util.BeanUtils;
import com.csair.invoice.common.base.util.CastUtil;
import com.csair.invoice.common.base.util.collection.CollectionUtil;
import com.csair.platform.cit.facade.exception.CitBizException;
import com.csair.platform.cit.facade.model.CitQueryParam;
import com.csair.platform.cit.facade.model.CitSendParam;
import com.csair.platform.cit.facade.model.a200000.A20000JpathEnum;
import com.csair.platform.cit.facade.model.a200000.declare.JmCzzsYjd2021SbxxFormVO;
import com.csair.platform.cit.facade.model.a202000.declare.FzjgxxGridlbVO;
import com.csair.platform.cit.facade.model.a202000.declare.ZjgxxFormVO;
import com.csair.platform.cit.service.biz.*;
import com.csair.platform.cit.service.biz.impl.InitBaseServiceImpl;
import com.csair.platform.cit.service.dao.CitJscgRepository;
import com.csair.platform.cit.service.dao.a200000.*;
import com.csair.platform.cit.service.entity.*;
import com.csair.platform.cit.service.util.JpathUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author zhengxincheng
 * 生成JpathService
 */
@Service
@Slf4j
public class JpathServiceImpl extends InitBaseServiceImpl {

    /**
     * 主表数据服务
     */
    @Autowired
    IA200000Service a200000Service;

    @Autowired
    ICitZcjszjkcmxbService iCitZcjszjkcmxbService;

    /**
     * 外国持股企业信息dao
     */
//    @Autowired
//    CitWgqyGridRepository wgqyGridDao;

    @Autowired
    ICitWgqyGridService iCitWgqyGridService;

    @Autowired
    CitWgqyGridFb1Repository fb1Dao;

    @Autowired
    CitWgqyGridFb2Repository fb2Dao;

    @Autowired
    CitWgqyGridFb3Repository fb3Dao;

    @Autowired
    CitWgqyGridFb4Repository fb4Dao;

    @Autowired
    CitJscgRepository jscgDao;

    @Autowired
    ICitZcjszjkcmxbService czsService;

    @Autowired
    ICitJscgService cjscgService;

    @Autowired
    IA202000Service a202000Service;

    public static final String GF = "91440000100017600N";

    public String getJpath(CitQueryParam queryParam){
        StringBuffer jpath = new StringBuffer();
        jpath.append("{");
        //申报信息1-24行
        String sbxx = getSbxxJpath(queryParam);
        //纳税人信息
        String nsrxx = getNsrxxJpath(queryParam);
        //其他信息
        String qxx   = getQtxxJpath(queryParam);
        //技术成果投资入股企业所得税递延纳税备案表
        String dynsbaGridlb = getJscgJpath(queryParam);
        //资产加速折旧、摊销（扣除）优惠接口
        //String czsGrid = czsService.getJpath(queryParam.getNsrsbh(), queryParam.getSkssqq(), queryParam.getSkssqz());
        //外国企业
        String wgqy =  getWgqyJpath(queryParam);
        //分配表 总机构信息
        String zjgxx = getZjgxxJpath(queryParam);
        //分配表 分机构信息
        String fjgxx = getFjgxxJpath(queryParam);

        jpath.append(nsrxx);
        jpath.append(sbxx);
        jpath.append(qxx);
        //jpath.append(dynsbaGridlb);
        //jpath.append(czsGrid);
        jpath.append(wgqy);
        jpath.append(zjgxx);
        jpath.append(fjgxx);
        String result = jpath.substring(0,jpath.length()-1);
        result+=("}");
        return result;
    }

    public String getFjgxxJpath(CitQueryParam queryParam) {
        if(!GF.equals(queryParam.getNsrsbh())){
            return "";
        }
        List<CitZjgxxForm> listZjgxx = a202000Service.queryZjgxx(queryParam.getNsrsbh(), queryParam.getSkssqq(), queryParam.getSkssqz());
        if(listZjgxx.isEmpty()){
            return "";
        }
        List<CitFzjgForm> zjgs = a202000Service.queryFzjgxx(listZjgxx.get(0).getId());
        List<FzjgxxGridlbVO> fzjgxxVo = new ArrayList<>();
        for (int i = 0 ; i < zjgs.size() ; i++) {
            Map<String, Object> mapFzjgxx = BeanUtils.json2Map(JSONObject.toJSONString(zjgs.get(i)));
            FzjgxxGridlbVO fzjgxx = BeanUtils.map2Bean(mapFzjgxx, FzjgxxGridlbVO.class);
            fzjgxxVo.add(fzjgxx);
        }
        return specialJpath(fzjgxxVo,A20000JpathEnum.FJGXX.KEY);
    }

    /**
     * 分配表，总机构信息
     * @param queryParam
     * @return
     */
    public String getZjgxxJpath(CitQueryParam queryParam){
        if(!GF.equals(queryParam.getNsrsbh())){
            return "";
        }
        List<CitZjgxxForm> listZjgxx = a202000Service.queryZjgxx(queryParam.getNsrsbh(), queryParam.getSkssqq(), queryParam.getSkssqz());
        if(listZjgxx.isEmpty()){
            return "";
        }
        CitZjgxxForm zjgxx = listZjgxx.get(0);
        Map<String, Object> mapZjgxx = BeanUtils.json2Map(JSONObject.toJSONString(zjgxx));
        ZjgxxFormVO zjgxxVo = BeanUtils.map2Bean(mapZjgxx, ZjgxxFormVO.class);
        return commonJpath(zjgxxVo,A20000JpathEnum.ZJGXX.KEY);
    }
    /**
     * 分配表
     * @param queryParam
     * @return
     */


    /**
     * 1.1.主表数据-纳税人信息
     *
     * \"ht_.ywbw.A200000Ywbd.nsrxx.nsrsbh\": \"91440000100005896P\",
     * \"ht_.ywbw.A200000Ywbd.nsrxx.skssqz\": \"2021-09-30\",
     * \"ht_.ywbw.A200000Ywbd.nsrxx.skssqq\": \"2021-07-01\",
     *
     */
    public String getNsrxxJpath(CitQueryParam queryParam){
        CitNsrxx nsrxx = a200000Service.queryNsrxx(queryParam.getNsrsbh(),queryParam.getSkssqq(),queryParam.getSkssqz()).get(0);
        return JpathUtils.getJpath(nsrxx);
    }

    /**
     * 《A200000中华人民共和国企业所得税月（季）度预缴纳税申报表（A类，2021年版）》 1-24 行
     *
     * @return
     */
    public String getSbxxJpath(CitQueryParam queryParam){
        CitSendParam param2 = new CitSendParam();
        BeanUtils.copyProperties(queryParam, param2);
        List<CitSbbxx> listSbbxx = a200000Service.querySbbxx(queryParam.getNsrsbh(),queryParam.getSkssqq(),queryParam.getSkssqz());
        CitSbbxx sbbxx = new CitSbbxx(); //数据库的申报主表
        if (CollectionUtil.isEmpty(listSbbxx)) {
            throw new CitBizException(7001,"主表没有数据, 请先保存数据");
        }else{
            sbbxx = listSbbxx.get(0);
        }

        Map<String, Object> mapSbbxx = BeanUtils.json2Map(JSONObject.toJSONString(sbbxx));
        //申报报文Vo对象
        JmCzzsYjd2021SbxxFormVO sbbxxVo = BeanUtils.map2Bean(mapSbbxx, JmCzzsYjd2021SbxxFormVO.class);

        sbbxxVo.setSfsyxxwlqy("N"); //是否属于小微利企业
        sbbxxVo.setSfkjxzxqy("");
        sbbxxVo.setSfgxjsqy("");
        sbbxxVo.setSffsjsrgdynssx("");
        sbbxxVo.setGjxzhjzhy("N"); //国家限制或禁止行业
        sbbxxVo.setYhjnsds("N"); //延缓缴纳所得税
        sbbxxVo.setQmcyrs(BigDecimal.ZERO); //期末从业人数
        sbbxxVo.setQccyrs(BigDecimal.ZERO); //期初从业人数
        sbbxxVo.setQczcze(BigDecimal.ZERO); //期初注册总额
        sbbxxVo.setQmzcze(BigDecimal.ZERO);
        CitYhfbxx yhfbxxVo = getYhfbxx(queryParam);
        if(yhfbxxVo != null) {
        	//把期初人数那些字段 填充进来
        	sbbxxVo.setQccyrs1(CastUtil.castBigDecimal(yhfbxxVo.getQccyrs1()));
        	sbbxxVo.setQccyrs2(CastUtil.castBigDecimal(yhfbxxVo.getQccyrs2()));
        	sbbxxVo.setQccyrs3(CastUtil.castBigDecimal(yhfbxxVo.getQccyrs3()));
        	sbbxxVo.setQccyrs4(CastUtil.castBigDecimal(yhfbxxVo.getQccyrs4()));
        	sbbxxVo.setQmcyrs1(CastUtil.castBigDecimal(yhfbxxVo.getQmcyrs1()));
        	sbbxxVo.setQmcyrs2(CastUtil.castBigDecimal(yhfbxxVo.getQmcyrs2()));
        	sbbxxVo.setQmcyrs3(CastUtil.castBigDecimal(yhfbxxVo.getQmcyrs3()));
        	sbbxxVo.setQmcyrs4(CastUtil.castBigDecimal(yhfbxxVo.getQmcyrs4()));
        	
        	sbbxxVo.setQczcze1(CastUtil.castBigDecimal(yhfbxxVo.getQczcze1()));
        	sbbxxVo.setQczcze2(CastUtil.castBigDecimal(yhfbxxVo.getQczcze2()));
        	sbbxxVo.setQczcze3(CastUtil.castBigDecimal(yhfbxxVo.getQczcze3()));
        	sbbxxVo.setQczcze4(CastUtil.castBigDecimal(yhfbxxVo.getQczcze4()));
        	sbbxxVo.setQmzcze1(CastUtil.castBigDecimal(yhfbxxVo.getQmzcze1()));
        	sbbxxVo.setQmzcze2(CastUtil.castBigDecimal(yhfbxxVo.getQmzcze2()));
        	sbbxxVo.setQmzcze3(CastUtil.castBigDecimal(yhfbxxVo.getQmzcze3()));
        	sbbxxVo.setQmzcze4(CastUtil.castBigDecimal(yhfbxxVo.getQmzcze4()));
        	sbbxxVo.setQycyrsQnpjrs(CastUtil.castBigDecimal(yhfbxxVo.getQycyrsQnpjrs()));
        	sbbxxVo.setZczeQnpjs(CastUtil.castBigDecimal(yhfbxxVo.getZczeQnpjs()));
        }
        return commonJpath(sbbxxVo, A20000JpathEnum.SBXX.KEY);
    }


    private CitYhfbxx getYhfbxx(CitQueryParam queryParam){
        //2.主表数据-优惠附表信息
        List<CitYhfbxx> listYhfbxx = a200000Service.queryYhfbxx(queryParam.getNsrsbh(), queryParam.getSkssqq(), queryParam.getSkssqz());
        if (CollectionUtil.isNotEmpty(listYhfbxx)) {
            return listYhfbxx.get(0);
        }
        return null;
    }

    //其他信息
    public String getQtxxJpath(CitQueryParam queryParam){
        //CitQtxx citQtxx = a200000Service.queryQtxx(queryParam.getNsrsbh(),queryParam.getSkssqq(),queryParam.getSkssqz()).get(0);
        StringBuilder jpath = new StringBuilder();
        String prefix = "ht_.ywbw.A200000Ywbd.qtxx";
        jpath.append("\"" + prefix + ".slr" +  "\": \"广东省电子税务局\",");
        jpath.append("\"" + prefix + ".slrq" +  "\": \"\",");
        return jpath.toString();
    }

    /**
     * 外国企业
     * @return
     */
    public String getWgqyJpath(CitQueryParam queryParam) {
        List<CitWgqyGrid> list = iCitWgqyGridService.getCitWgqyGrid(queryParam.getNsrsbh(), queryParam.getSkssqq(), queryParam.getSkssqz());

        StringBuffer jpath = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            CitWgqyGrid citWgqyGrid = list.get(i);
            citWgqyGrid.setMxxh(i+1);

            jpath.append(getWgqy1Jpath(citWgqyGrid.getId(),i));
            jpath.append(getWgqy2Jpath(citWgqyGrid.getId(),i));
            jpath.append(getWgqy3Jpath(citWgqyGrid.getId(),i));
            jpath.append(getWgqy4Jpath(citWgqyGrid.getId(),i));
        }
        jpath.append(JpathUtils.getJpath(list));
        return jpath.toString();
    }

    /**
     * 获取外国企业 附表1数据
     * @return
     */
    public String getWgqy1Jpath(Long parentId,Integer number){
        List<CitWgqyGridFb1> fb1Data= fb1Dao.queryByParentId(parentId);
        for (int j = 0; j < fb1Data.size(); j++) {
            CitWgqyGridFb1 fb1 = fb1Data.get(j);
            fb1.setMxxh(j+1);
        }
        return JpathUtils.getJpath(fb1Data,number);
    }

    public String getWgqy2Jpath(Long parentId,Integer number){
        List<CitWgqyGridFb2> fb2Data= fb2Dao.queryByParentId(parentId);
        for (int j = 0; j < fb2Data.size(); j++) {
            CitWgqyGridFb2 fb2 = fb2Data.get(j);
            fb2.setMxxh(j+1);
        }
        return JpathUtils.getJpath(fb2Data,number);
    }

    public String getWgqy3Jpath(Long parentId,Integer number){
        List<CitWgqyGridFb3> fb3Data= fb3Dao.queryByParentId(parentId);
        for (int j = 0; j < fb3Data.size(); j++) {
            CitWgqyGridFb3 fb3 = fb3Data.get(j);
            fb3.setMxxh(j+1);
        }
        return JpathUtils.getJpath(fb3Data,number);
    }

    public String getWgqy4Jpath(Long parentId,Integer number){
        List<CitWgqyGridFb4> fb4Data= fb4Dao.queryByParentId(parentId);
        for (int j = 0; j < fb4Data.size(); j++) {
            CitWgqyGridFb4 fb4 = fb4Data.get(j);
            fb4.setMxxh(j+1);
        }
        return JpathUtils.getJpath(fb4Data,number);
    }

    public String commonJpath(Object obj,String prefix){
        Map<String, Object> objMap = BeanUtil.beanToMap(obj);
        StringBuilder jpath = new StringBuilder();
        for(Map.Entry<String, Object> entry : objMap.entrySet()){
            if(entry.getValue() instanceof String){
                jpath.append("\"" + prefix + "." + entry.getKey() + "\": \"" + entry.getValue() + "\",");
            }else{
                jpath.append("\"" + prefix + "." + entry.getKey() + "\": " + entry.getValue() + ",");
            }
        }
        return jpath.toString();
    }

    public String specialJpath(List list,String prefix){
        JSONArray data = JSONArray.parseArray(JSONObject.toJSONString(list));
        StringBuilder jpath = new StringBuilder();

        for (int i = 0 ; i < data.size() ; i++) {
            JSONObject object = data.getJSONObject(i);
            Map<String, Object> map = BeanUtils.json2Map(object.toJSONString());
            for (Map.Entry<String, Object> entry : map.entrySet()){
                String key = entry.getKey();
                Object valueObj = entry.getValue();
                if (valueObj instanceof String) {
                    jpath.append("\"" + prefix + "[" + i + "]." + key + "\": \"" + valueObj.toString() + "\",");
                } else {
                    jpath.append("\"" + prefix + "[" + i + "]." + key + "\": " + valueObj.toString() + ",");
                }
            }
        }
        return jpath.toString();
    }

    /**
     * 获取技术成果投资入股企业所得税递延纳税备案表
     * @return
     */
    public String getJscgJpath(CitQueryParam param) {
        List<CitJscg> jscgs = cjscgService.queryByNsrsbhAndSkssqqAndSkssqz(param.getNsrsbh(), param.getSkssqq(), param.getSkssqz());
        if (CollectionUtil.isEmpty(jscgs)) {
            return "";
        }
        Iterator<CitJscg> it = jscgs.iterator();
        while (it.hasNext()){
            CitJscg jscg = it.next();
            if("合计".equals(jscg.getHc())){
                it.remove();
            }
        }
        if (CollectionUtil.isEmpty(jscgs)) {
            return "";
        }
        return JpathUtils.getJpath(jscgs);
    }
}
